package com.example.hello.service.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.example.hello.mapper.SMSCodeMapper;
import com.example.hello.mapper.UserBookMapper;
import com.example.hello.mapper.UserMapper;
import com.example.hello.pojo.SMSCode;
import com.example.hello.pojo.User;
import com.example.hello.service.SMSService;
import com.example.hello.util.AliSmsOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Random;

/**
 * 短信验证码业务逻辑实现
 */
@Service
public class SMSServiceImpl implements SMSService {

    @Autowired
    private SMSCodeMapper smsCodeMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean sendSMSCode(String phone) {

        // 查询该手机号最近一次的验证码记录
        SMSCode latestCode = smsCodeMapper.getLatestCodeByPhone(phone);
        Date now = new Date();

//         如果存在记录且距离上次发送不足60秒，则拒绝重复发送
        if (latestCode != null) {
            long diff = now.getTime() - latestCode.getSendTime().getTime();
            if (diff < 60 * 1000) {
                return false;
            }
        }

        // 生成6位随机验证码（不足6位补零）
        String code = String.format("%06d", new Random().nextInt(999999));

        // 模拟调用短信平台发送短信（实际场景下需要集成第三方短信 API）
        System.out.println("【短信服务】发送验证码 " + code + " 到手机号 " + phone);

        try {
            // 调用阿里云短信服务发送验证码
            SendSmsResponse response = new AliSmsOperator().sendSms(phone, code);
            // 判断返回结果是否成功，阿里云返回码 "OK" 表示成功
            if (!"OK".equals(response.getCode())) {
                System.err.println("短信发送失败: " + response.getMessage());
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        // 设置验证码过期时间（例如5分钟后）
        Date expireTime = new Date(now.getTime() + 5 * 60 * 1000);

        SMSCode smsCode = new SMSCode();
        smsCode.setPhone(phone);
        smsCode.setCode(code);
        smsCode.setSendTime(now);
        smsCode.setExpireTime(expireTime);
        smsCode.setStatus(0); // 0：未使用

        // 插入验证码记录
        smsCodeMapper.insertSMSCode(smsCode);
        return true;
    }

    @Override
    public boolean verifySMSCode(String phone, String code) {
        // 获取该手机号最新的验证码记录
        SMSCode latestCode = smsCodeMapper.getLatestCodeByPhone(phone);
        Date now = new Date();
        if (latestCode == null) {
            return false;
        }
        // 判断验证码是否匹配、是否在有效期内、且状态为未使用
        if (latestCode.getCode().equals(code) && now.before(latestCode.getExpireTime()) && latestCode.getStatus() == 0) {
            // 验证通过后更新状态为已使用，防止重复使用
            smsCodeMapper.updateStatus(latestCode.getId());
            return true;
        }
        return false;
    }
}